<?php
namespace App\Models;

class ShopAccount extends BaseModel
{
    protected $table = "shop_account";

    protected $rules = [
        'account_name' => 'required|between:3,20|unique:shop_account,account_name',
        'password' => 'required|between:6,30',
        'confirm_password' => 'required|same:password'
    ];

    protected $message = [
        'account_name.required' => '账号必须填写',
        'account_name.between' => '账号长度不合法，应为3-20位字符',
        'account_name.unique' => '此账号已存在，请重新输入',
        'password.required' => '密码必须填写',
        'password.between' => '密码长度不合法，应为6-30位字符',
        'confirm_password.required' => '确认密码必填',
        'confirm.same' => '两次密码不一致',
    ];

    protected $shopRules = [
        'shop_name' => 'required|between:1,15|unique:shop,shop_name',
        'boss_name' => 'required|between:1,5',
        'shop_phone' => 'required|regex:/^1[3456789]{1}\d{9}$/',
        'province_id' => 'required|digits:6',
        'city_id' => 'digits:6',
        'area_id' => 'required|digits:6',
        'area_info' => 'required',
        'address' => 'required|between:1,50',
    ];

    protected $shopMsg = [
        'shop_name.required' => '店铺名称必须填写',
        'shop_name.between' => '店铺名称不能超过15个字',
        'shop_name.unique' => '该店铺名称已存在，请重新输入',
        'boss_name.required' => '经营者姓名称必须填写',
        'boss_name.between' => '经营者姓名不能超过5个字',
        'shop_phone.required' => '联系方式必须填写',
        'shop_phone.regex' => '请输入正确的手机号',
        'province_id.required' => '请选择所属省份',
        'province_id.digits' => '非法数据',
        'city_id.digits' => '非法数据',
        'area_id.required' => '请选择所属区域',
        'area_id.digits' => '非法数据',
        'area_info.required' => '请选择所属地区',
        'address.required' => '店铺详细地址必须填写',
        'address.between' => '店铺详细地址不能超过50个字',
    ];

    public function addOrUpdate()
    {
        $data['account_name'] = request('account_name');
        $data['password'] = trim(request('password'));
        $data['old_password'] = trim(request('old_password',''));
        $data['confirm_password'] = trim(request('confirm_password'));
        $data['shop_id'] = request('shop_id');
        $data['admin_id'] = request('admin_id') ? intval(request('admin_id')) : is_login();

        if($data['old_password'] === $data['password']) {
            $this->error = '新密码不能与旧密码一致';
            return false;
        }

        if(request('id')) {
            $this->rules['account_name'] .= ','.request('id').',id,admin_id,'.$data['admin_id'];
            $info = $this->_getOneById(intval(request('id')));
            if(!$info) {
                $this->error = '非法操作';
                return false;
            } else {
                if($info['password'] != md5($data['old_password'])) {
                    $this->error = '原密码不正确';
                    return false;
                }
            }
        }

        $validator = $this->_validate($data);
        if (!$validator) {
            return false;
        }

        unset($data['old_password']);
        unset($data['confirm_password']);
        $data['password'] = md5($data['password']);
        if(!request('id')) {
            $data['created_at'] = date('Y-m-d H:i:s');
            $res = $this->_add($data);
        } else {
            $res = $this->_update(['id'=>request('id')], $data);
        }
        if(!$res) {
            $this->error = '保存失败';
            return false;
        }
        return $res;
    }

    public function login()
    {
        $username = request('username');
        $password = request('password');
        $where['account_name'] = $username;
        $account = $this->_getOne($where);
        if (!$account) {
            $this->error = '用户不存在或已被禁用！'; //应用级别禁用
            return false;
        }
        if (md5($password) !== $account['password']) {
            $this->error = '账号或密码错误';
            return false;
        }
        $this->updateLogin($account);
        $menu = new Menu();
        addSession('menus', $menu->getMenus('account'));

        $shopModel = new Shop();
        $condition['admin_id'] = $account['admin_id'];
        $time = strtotime(date('Y-m-d')) + 3600*24*7;
        $condition['end_time'] = ['<', $time];
        $res = $shopModel->_getOne($condition, 'id');
        if ($res) {
            addSession('show_notice', 1);
        }

        // 记录行为
        $actionLogModel = new ActionLog();
        $actionLogModel->action_log('admin_login', 'shop_account', $account['id'], $account['id']);
        return true;
    }

    protected function updateLogin($account)
    {
        /* 记录登录SESSION和COOKIES */
        $auth = [
            'id' => $account['id'],
            'admin_id' => $account['admin_id'],
            'shop_id' => $account['shop_id'],
            'account_name' => $account['account_name']
        ];
        session(['account' => $auth]);
        session(['account_sign' => data_auth_sign($auth)]);
        addSession('platIdentify','account'); // 设置平台标识
    }

    public function addAccountAndShop()
    {
        $currentTime = date('Y-m-d H:i:s');
        $admin_id = 2;
        $data['shop_name'] = trim(request('shop_name'));
        $data['boss_name'] = trim(request('boss_name'));
        $data['shop_phone'] = trim(request('shop_phone'));
        $data['province_id'] = request('province');
        $data['area_id'] = request('area');
        $data['area_info'] = request('area_info');
        $data['address'] = trim(request('address'));
        $data['addtime'] = time();
        $data['admin_id'] = $admin_id;
        $data['created_at'] = $currentTime;
        $data['status'] = 1; //初期使用免费开放，后期更改为0
        $data['start_time'] = time(); //初期使用免费开放，后期更改为0
        $data['end_time'] = strtotime(date("y-m-d", strtotime("+16 days"))); //初期使用免费开放15天，后期更改为0
        if (request('city')) {
            $data['city_id'] = trim(request('city'));
        }
        if (!$this->_validate($data, 'shopRules', 'shopMsg')) {
            return false;
        }
        $password = '123456';
        $accountData['account_name'] = request('account_name');
        $accountData['password'] = $password;
        $accountData['confirm_password'] = $password;
        if(!$this->_validate($accountData)){
            return false;
        }
        $this->_start();
        try{
            $res = (new Shop())->_save($data);
            unset($accountData['confirm_password']);
            $accountData['password'] = md5($password);
            $accountData['admin_id'] = $admin_id;
            $accountData['shop_id'] = $res;
            $accountData['created_at'] = $currentTime;
            $this->_add($accountData);
        }catch (\Exception $e){
            $this->_rollBack();
            return false;
        }
        $this->_commit();
        return true;
    }
}
